<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Api\V1;

use Think\Exception;

class GetSession
{
    public $login = false; //是否需要登录才能访问该接口
    public $title = "获取小程序登录数据";
    public $group = '小程序首页';
    public $desc = "";

    public $input = [
        'code' => 'required;label=code;',
        'referer_id' => 'label=推荐人id;',
    ];

    public $output = [
        'api_token' => 'label=接口token;comment=用户登录状态标识,通过header参数API-TOKEN=api_token提交;',
        'expire_time' => 'label=接口token过期时间;',
        'session_key' => 'label=session_key;',
        'openid' => 'label=openid;',
        'uid' => 'label=用户id;',
        'username' => 'label=用户名;',
        'mobile' => 'label=手机号;',
    ];

    public function run($param, $uid)
    {
        $appid = 'wx899ad8ca0a9fd507';
        $secret = '2f23848e4e407c02972f19434c3c9a3d';

        $url="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&grant_type=authorization_code&js_code=".$param['code'];
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_HEADER,         false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $exec = curl_exec($curl);curl_close($curl);
        $json = json_decode($exec, true);
        if(isset($json['session_key'])){
            $user = M('user')->where(['openid' => $json['openid']])->find();
            if(isset($user['uid'])){//生成token
                $ucenter = M('ucenter_member')->where(['id' => $user['uid']])->find();
                //生成Token
                list($api_token, $expire_time) = OE('user')->genApiToken($user['uid']);
                $result = [
                    'api_token' => $api_token,
                    'expire_time' => $expire_time,
                    'session_key' => $json['session_key'],
                    'openid' => $json['openid'],
                    'uid' => $user['uid'],
                    'username' => $ucenter['username'],
                ];
            }else{ //注册
                $param['openid'] = $json['openid'];
                $flag = OE('user')->register3($param);
                if($flag['code'] == 0){
                    $result =$flag['data'];
                }else{
                    throw new Exception('注册用户信息失败');
                }

            }

        }else{
            throw new Exception('生成session_key失败');
        }
        return $result;
    }
}
